﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class ScannerLib
    {

        private SerialPort serialPort;

        public event EventHandler CodeRcvEvent;

        public void Connect(string portName, int baudRate, Parity parity, int databits, StopBits stopBits)
        {
            serialPort = new SerialPort(portName, baudRate, parity, databits, stopBits);

            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }

            // 设置接收字节数阈值,即每次接收至少1个字节数据时触发DataReceived事件，默认值也为1
            serialPort.ReceivedBytesThreshold = 1;
            serialPort.DataReceived += SerialPort_DataReceived;

            serialPort.Open();
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int count = serialPort.BytesToRead;

            byte[] buffer = new byte[count];

            serialPort.Read(buffer, 0, count);

            string message = Encoding.Default.GetString(buffer);

            CodeRcvEvent?.Invoke(message, null);


        }

        public void Disconnect()
        {
            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }
        }

        public void Send(string code)
        {
            serialPort?.Write(code);
        }
    }
}
